package cn.iocoder.yudao.module.member.controller.app.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.ip.core.utils.IPUtils;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.member.controller.app.user.vo.*;
import cn.iocoder.yudao.module.member.convert.user.MemberUserConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.level.MemberLevelDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.service.level.MemberLevelService;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import cn.iocoder.yudao.module.system.enums.common.SexEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

@Tag(name = "用户 APP - 用户个人中心")
@RestController
@RequestMapping("/member/user")
@Validated
@Slf4j
public class AppMemberUserController {

    @Resource
    private MemberUserService userService;
    @Resource
    private MemberLevelService levelService;

    @GetMapping("/get")
    @Operation(summary = "获得基本信息")
    @PreAuthenticated
    public CommonResult<AppMemberUserInfoRespVO> getUserInfo() {
        MemberUserDO user = userService.getUser(getLoginUserId());
        MemberLevelDO level = levelService.getLevel(user.getLevelId());
        AppMemberUserInfoRespVO userInfoRespVO = MemberUserConvert.INSTANCE.convert(user, level);
        if(userInfoRespVO.getVipEndTime() == null){
            userInfoRespVO.setIsVip(false);
        }else{
            userInfoRespVO.setIsVip(userInfoRespVO.getVipEndTime().isAfter(DateUtil.toLocalDateTime(DateUtil.date())));
        }
        return success(userInfoRespVO);
    }

    @GetMapping("/getWeekTopList")
    @Operation(summary = "获得榜单列表")
    public CommonResult<Map<String, List<MemberUserDO>>> getWeekTopList() {
        Map<String, List<MemberUserDO>> data = new HashMap<>();
        List<MemberUserDO> maleWeekTopList = userService.getWeekTopList(SexEnum.MALE.getSex());
        List<MemberUserDO> femaleWeekTopList = userService.getWeekTopList(SexEnum.FEMALE.getSex());
        data.put("maleWeekTopList", maleWeekTopList);
        data.put("femaleWeekTopList", femaleWeekTopList);
        return success(data);
    }

    @GetMapping("/getHomeData")
    @Operation(summary = "获得首页信息")
    public CommonResult<Map<String,Object>> getHomeData() {
        Map<String, Object> data = new HashMap<>();
        List<MemberUserDO> memberHotList = userService.getMemberHotList();
        List<MemberUserDO> memberNewList = userService.getMemberNewList();
        data.put("memberHotList", memberHotList);
        data.put("memberNewList", memberNewList);
        return success(data);
    }

    @GetMapping("/getByUserId")
    @Operation(summary = "获得基本信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<AppMemberUserInfoRespVO> getUserInfoByUserId(@RequestParam("id") Long id) {
        MemberUserDO user = userService.getUser(id);
        userService.updateUserVisitNum(id);
        return success(MemberUserConvert.INSTANCE.convert04(user));
    }

    @GetMapping("/getQrcodeByUserId")
    @Operation(summary = "获得交友名片")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthenticated
    public CommonResult<String> getQrcodeByUserId(@RequestParam("id") Long id) {
        return success(userService.getQrcodeByUserId(getLoginUserId(), id));
    }

    @PutMapping("/update")
    @Operation(summary = "修改基本信息")
    @PreAuthenticated
    public CommonResult<Boolean> updateUser(@RequestBody @Valid AppMemberUserUpdateReqVO reqVO) {
        userService.updateUser(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-mobile")
    @Operation(summary = "修改用户手机")
    @PreAuthenticated
    public CommonResult<Boolean> updateUserMobile(@RequestBody @Valid AppMemberUserUpdateMobileReqVO reqVO) {
        userService.updateUserMobile(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-mobile-by-weixin")
    @Operation(summary = "基于微信小程序的授权码，修改用户手机")
    @PreAuthenticated
    public CommonResult<Boolean> updateUserMobileByWeixin(@RequestBody @Valid AppMemberUserUpdateMobileByWeixinReqVO reqVO) {
        userService.updateUserMobileByWeixin(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-password")
    @Operation(summary = "修改用户密码", description = "用户修改密码时使用")
    @PreAuthenticated
    public CommonResult<Boolean> updateUserPassword(@RequestBody @Valid AppMemberUserUpdatePasswordReqVO reqVO) {
        userService.updateUserPassword(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/slashed")
    @Operation(summary = "用户置顶")
    @PreAuthenticated
    public CommonResult<Boolean> updateUserSlashed() {
        userService.updateUserSlashed(getLoginUserId());
        return success(true);
    }

    @PutMapping("/reset-password")
    @Operation(summary = "重置密码", description = "用户忘记密码时使用")
    public CommonResult<Boolean> resetUserPassword(@RequestBody @Valid AppMemberUserResetPasswordReqVO reqVO) {
        userService.resetUserPassword(reqVO);
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得会员分页")
    public CommonResult<PageResult<AppMemberUserInfoRespVO>> getMemberUserInfoPage(@Valid AppMemberUserInfoPageReqVO pageReqVO) {
        if(pageReqVO.getSex() != null){
            if(pageReqVO.getSex() == 2){
                pageReqVO.setSex(1);
            }else{
                pageReqVO.setSex(2);
            }
        }

        MemberUserDO memberUserDO = null;
        if(pageReqVO.getUserId() != null){
            memberUserDO = userService.getUser(pageReqVO.getUserId());
        }

        if(pageReqVO.getIsCity() != null){
            if(CommonStatusEnum.ENABLE.getStatus().equals(pageReqVO.getIsCity())){
                if(memberUserDO != null){
                    if(memberUserDO.getVipEndTime() == null){
                        throw exception(MEMBER_VIP_CITY);
                    }else{
                        if(memberUserDO.getVipEndTime().isBefore(DateUtil.toLocalDateTime(DateUtil.date()))){
                            throw exception(MEMBER_VIP_CITY);
                        }
                    }
                }
                pageReqVO.setCity(IPUtils.getArea(getClientIP()).getName());
            }
        }

        if(StringUtils.isNotBlank(pageReqVO.getCity())){
            if(memberUserDO != null){
                if(memberUserDO.getVipEndTime() == null){
                    throw exception(MEMBER_VIP_CITY);
                }else{
                    if(memberUserDO.getVipEndTime().isBefore(DateUtil.toLocalDateTime(DateUtil.date()))){
                        throw exception(MEMBER_VIP_CITY);
                    }
                }
            }
        }

        if(pageReqVO.getMaxAge() == null || pageReqVO.getMinAge() == null){
            pageReqVO.setMinAge(18);
            pageReqVO.setMaxAge(50);
        }

        PageResult<MemberUserDO> pageResult = userService.getMemberUserInfoPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }

        PageResult<AppMemberUserInfoRespVO> page = BeanUtils.toBean(pageResult, AppMemberUserInfoRespVO.class);

        for (AppMemberUserInfoRespVO member : page.getList()){
            long regDay = DateUtil.betweenDay(new DateTime(member.getCreateTime()), DateUtil.date(), false);
            member.setDay(regDay);
            DateTime endDate = DateUtil.date();
            DateTime beginDate = DateUtil.offsetMinute(DateUtil.date(), -5);
            member.setOnline(DateUtil.isIn(new DateTime(member.getUpdateTime()), beginDate, endDate));
        }
        return success(page);
    }

}

